<template>
  <div class="container">
    <div class="app-container">
      <!--   角色管理内容   -->
      <div class="role-operate">
        <!--   添加角色按钮   -->
        <add-button @click.native="openDialog" />
      </div>
      <!--     放置table组件  -->
      <my-loading v-if="list.length===0&&!timeout" />
      <el-table v-else :data="list" stripe border>
        <!--    放置列  -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template v-slot="{ row }">
            <!--  条件的判断  -->
            <el-input v-if="row.isEdit" v-model="row.curName" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.curState" />
            <span v-else style="margin-left: 10px">
              <el-tag v-if="row.state" type="success" effect="dark">已启用</el-tag>
              <el-tag v-else type="danger" effect="dark">未启用</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.curDescription" size="mini" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="300" label="操作">
          <!--          操作按钮-->
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" round @click="updateRole(row)">确认</el-button>
              <el-button type="danger" size="mini" round @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <!--              非编辑状态-->
              <!--     权限       -->
              <el-button type="success" icon="el-icon-setting" circle @click="btnPermission(row.id)" />
              <!--     编辑        -->
              <el-button type="primary" icon="el-icon-edit" circle @click="handleEdit(row)" />
              <!--     删除        -->
              <el-button type="danger" icon="el-icon-delete" circle @click="deleteRole(row.id)" />
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!--            放置分页组件  -->
      <el-row type="flex" align="middle" style="height: 60px;" justify="end">
        <span>共 <span style="color: cornflowerblue">{{ pageParams.total }}</span> 条 </span>
        <el-pagination
          :page-size="pageParams.pagesize"
          layout="prev, pager, next"
          :total="pageParams.total"
          :current-page="pageParams.page"
          background
          :default-checked-keys="permIds"
          @current-change="changePage"
        >
          <!--        放置页码 -->
        </el-pagination>
      </el-row>
    </div>
    <!--    放置添加角色弹层  -->
    <role-dialog :show-dialog.sync="showDialog" @updateRole="getRoleList" />
    <!--    放置权限弹层 -->
    <el-dialog
      :visible.sync="showPermissionDialog"
      :close-on-click-modal="false"
      title="分配权限"
    >
      <my-loading v-if="permIdsLoading" />
      <template v-else>
        <el-tree
          ref="permissionTree"
          :default-checked-keys="permIds"
          node-key="id"
          default-expand-all
          :data="permissionTree"
          :props="{ label: 'name' }"
          show-checkbox
        />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="mini" type="primary" @click="btnPermissionOk">确定</el-button>
            <el-button size="mini" @click="showPermissionDialog=false">取消</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import AddButton from '@/views/role/components/add-button.vue'
import { assignPrem, deleteRole, getRoleDetail, getRoleList, updateRole } from '@/api/role'
import RoleDialog from '@/views/role/components/role-dialog.vue'
import { getPermissionList } from '@/api/permission'
import { transListToTree } from '@/utils'

export default {
  name: 'Role',
  components: { RoleDialog, AddButton },
  data() {
    return {
      list: [],
      pageParams: {
        page: 1, // 第几页
        pagesize: 10, // 每页多少条
        total: 0
      },
      showDialog: false,
      timeout: false,
      showPermissionDialog: false,
      permissionTree: [],
      curRoleId: null,
      permIds: [],
      permIdsLoading: false
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      this.list = []
      this.timeout = false
      setTimeout(() => {
        this.timeout = true
      }, 3 * 1000)
      const { rows, total } = await getRoleList(this.pageParams)
      this.list = rows
      this.pageParams.total = total
      // 初始化编辑状态
      this.list.forEach((item) => {
        /**
         * 动态添加属性不具备响应式的特点
         * 数据响应式 数据变化 页面会自动更新
         *
         */
        // item.isEdit = false
        this.$set(item, 'isEdit', false)
        this.$set(item, 'curName', item.name)
        this.$set(item, 'curState', item.state === 1)
        this.$set(item, 'curDescription', item.description)
      })
    },
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getRoleList()
    },
    openDialog() {
      this.showDialog = true
    },
    handleEdit(row) {
      row.isEdit = true
    },
    async updateRole(row) {
      console.log(row)
      // 修改角色
      await updateRole(row.id, {
        id: row.id,
        name: row.curName,
        state: row.curState ? 1 : 0,
        description: row.curDescription
      })
      // row.isEdit = false
      this.getRoleList()
    },
    deleteRole(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteRole(id)
        // 如果当前页只有一条数据，删除之后，页码应该-1
        if (this.list.length === 1 && this.pageParams.page > 1) {
          this.pageParams.page--
        }
        await this.getRoleList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async btnPermission(id) {
      this.permIdsLoading = true
      this.showPermissionDialog = true
      this.curRoleId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      console.log(permIds)
      this.permissionTree = transListToTree(await getPermissionList(), 0)
      // console.log(this.permissionTree)
      this.permIdsLoading = false
    },
    // 点击确定时触发
    async btnPermissionOk() {
      // console.log(this.$refs.permissionTree.getCheckedKeys())
      await assignPrem({
        id: this.curRoleId,
        permIds: this.$refs.permissionTree.getCheckedKeys()
      })
      this.$notify({
        title: '操作成功',
        message: '分配权限成功',
        type: 'success'
      })
      this.showPermissionDialog = false
    }
  }
}
</script>

<style scoped lang="scss">
.role-operate {
  padding: 10px;
}
</style>
